package com.thesis.manage.service.impl;

import com.github.crab2died.ExcelUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thesis.manage.common.constant.YesOrNoEnum;
import com.thesis.manage.common.exception.CommonException;
import com.thesis.manage.common.service.impl.BaseServiceImpl;
import com.thesis.manage.domain.College;
import com.thesis.manage.domain.Teacher;
import com.thesis.manage.domain.TeacherRole;
import com.thesis.manage.mapper.TeacherMapper;
import com.thesis.manage.service.CollegeService;
import com.thesis.manage.service.TeacherRoleService;
import com.thesis.manage.service.TeacherService;
import com.thesis.manage.service.constant.ErrorMessage;
import com.thesis.manage.service.model.RoleEnum;
import com.thesis.manage.service.model.UserActivityStateEnum;
import com.thesis.manage.service.module.excel.TeacherExcel;
import com.thesis.manage.service.module.vo.TeacherVO;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.common.Mapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author php
 * @date 2018/1/23
 */
@Service
public class TeacherServiceImpl extends BaseServiceImpl<Teacher> implements TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private CollegeService collegeService;

    @Resource
    private TeacherRoleService teacherRoleService;


    @Override
    protected Mapper<Teacher> getMapper() {
        return this.teacherMapper;
    }

    @Override
    protected Class<Teacher> getEntityClass() {
        return Teacher.class;
    }

    @Override
    public void importExcel(MultipartFile file) {
        // TODO: 2018/1/26 使用多线程去导入数据 （等待优化）
        Assert.notNull(file, ErrorMessage.REQUEST_SELECT_FILE);
        try {
            List<TeacherExcel> teacherExcels = ExcelUtils.getInstance().readExcel2Objects(file.getInputStream(), TeacherExcel.class);
            /*
            对象转换
             */
            if (CollectionUtils.isNotEmpty(teacherExcels)) {
                Teacher teacher;
                for (TeacherExcel teacherExcel : teacherExcels) {
                    teacher = new Teacher();
                    PropertyUtils.copyProperties(teacher, teacherExcel);
                    if (this.isNotExist(teacher.getTeacherNumber())) {
                        College college = this.collegeService.findByName(teacher.getCollegeName());
                        if (college != null) {
                            teacher.setCollegeId(college.getId());
                        }
                        teacher.setPassword(DigestUtils.md5DigestAsHex(teacher.getIdCard().getBytes()));
                        teacher.setStatus(UserActivityStateEnum.OFF_LINE.getValue());
                        this.save(teacher);
                    }
                }
            }
        } catch (Exception e) {
            throw new CommonException("file import failed", ErrorMessage.FILE_IMPORT_FAILED);
        }
    }

    @Override
    public void authorization(Long id, Integer isAuth, Long rid) {
        Teacher one = this.findById(id);
        Assert.notNull(one, ErrorMessage.DATA_NO_EXIST);
        TeacherRole role = new TeacherRole();
        role.setTeacherId(id);
        role.setRoleId(rid);
        role.setCollegeName(one.getCollegeName());
        //授权
        if (YesOrNoEnum.YES.getValue().intValue() == isAuth) {
            this.teacherRoleService.save(role);
        } else if (YesOrNoEnum.NO.getValue().intValue() == isAuth) {
            //取消授权
            TeacherRole teacherRole = this.teacherRoleService.findByOne(role);
            if (teacherRole != null) {
                this.teacherRoleService.delete(teacherRole.getId());
            }
        }
    }

    @Override
    public PageInfo<TeacherVO> detail(Pageable pageable) {
        List<TeacherVO> teacherVOS = new ArrayList<>();
        PageInfo<Teacher> list = this.list(pageable);
        PageInfo<TeacherVO> objectPageInfo = new PageInfo<>();
        try {
            if (list != null && CollectionUtils.isNotEmpty(list.getList())) {
                TeacherVO teacherVO;
                for (Teacher teacher : list.getList()) {
                    teacherVO = new TeacherVO();
                    List<Integer> roles = this.teacherRoleService.findRolesByTeacherId(teacher.getId());
                    PropertyUtils.copyProperties(teacherVO, teacher);
                    teacherVO.setAuth(roles.contains(RoleEnum.LEADER.getValue()));
                    teacherVOS.add(teacherVO);
                }
                objectPageInfo.setTotal(list.getTotal());
                objectPageInfo.setList(teacherVOS);
                objectPageInfo.setPageNum(list.getPageNum());
                objectPageInfo.setPageSize(list.getPageSize());
                objectPageInfo.setPages(list.getPages());
            }
        } catch (Exception e) {
            throw new CommonException("data covert failed", "教师信息转换失败");
        }
        return objectPageInfo;
    }

    @Override
    public TeacherVO info(Long id) {
        Teacher teacher = this.findById(id);
        teacher.setPassword(null);
        String roles = this.teacherRoleService.findRoles(id);
        TeacherVO teacherVO = new TeacherVO();
        try {
            PropertyUtils.copyProperties(teacherVO, teacher);
            teacherVO.setPermissions(roles);
        } catch (Exception e) {
            throw new CommonException("data.covert.failed", ErrorMessage.OBJECT_CONVERT_FAILED);
        }
        return teacherVO;
    }

    @Override
    public PageInfo<TeacherVO> listByCollegeName(String collegeName, Pageable pageable) {
        Assert.notNull(collegeName, ErrorMessage.PARAMS_IS_NULL);
        List<TeacherVO> teacherVOS = new ArrayList<>();
        PageInfo<TeacherVO> objectPageInfo = new PageInfo<>();
        if (pageable == null) {
            PageHelper.startPage(1, 10);
        } else {
            PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());
        }
        Teacher teacher = new Teacher();
        teacher.setCollegeName(collegeName);
        teacher.setDelStatus(YesOrNoEnum.NO.getValue());
        List<Teacher> list = this.teacherMapper.select(teacher);
        PageInfo<Teacher> pageInfo = new PageInfo<>(list);
        try {
            if (CollectionUtils.isNotEmpty(pageInfo.getList())) {
                TeacherVO teacherVO;
                for (Teacher t : pageInfo.getList()) {
                    teacherVO = new TeacherVO();
                    List<Integer> roles = this.teacherRoleService.findRolesByTeacherId(t.getId());
                    teacherVO.setName(t.getName());
                    teacherVO.setImage(t.getImage());
                    teacherVO.setId(t.getId());
                    teacherVO.setTeacherNumber(t.getTeacherNumber());
                    teacherVO.setAuth(roles.contains(RoleEnum.GUIDETEACHER.getValue()));
                    teacherVOS.add(teacherVO);
                }
                objectPageInfo.setTotal(pageInfo.getTotal());
                objectPageInfo.setList(teacherVOS);
                objectPageInfo.setPageNum(pageInfo.getPageNum());
                objectPageInfo.setPageSize(pageInfo.getPageSize());
                objectPageInfo.setPages(pageInfo.getPages());
            }
        } catch (Exception e) {
            throw new CommonException("data covert failed", "教师信息转换失败");
        }
        return objectPageInfo;
    }


    /**
     * 验证老师是否存在
     *
     * @param teacherNumber 老师名称
     * @return boolean
     */
    private boolean isNotExist(String teacherNumber) {
        return this.findByTeacherNumber(teacherNumber) == null;
    }

    @Override
    public Teacher findByTeacherNumber(String teacherNumber) {
        Assert.notNull(teacherNumber, ErrorMessage.PARAMS_IS_NULL);
        Teacher teacher = new Teacher();
        teacher.setTeacherNumber(teacherNumber);
        teacher.setDelStatus(YesOrNoEnum.NO.getValue());
        return this.teacherMapper.selectOne(teacher);
    }

//    /**
//     * 对象转换
//     *
//     * @param teacherExcels 转换对象
//     * @return list<Teacher>
//     */
//    private List<Teacher> convert(List<TeacherExcel> teacherExcels) {
//        List<Teacher> list = new ArrayList<>();
//        try {
//            if (CollectionUtils.isNotEmpty(teacherExcels)) {
//                Teacher teacher;
//                for (TeacherExcel teacherExcel : teacherExcels) {
//                    teacher = new Teacher();
//                    PropertyUtils.copyProperties(teacher, teacherExcel);
//                    list.add(teacher);
//                }
//            }
//            return list;
//        } catch (Exception e) {
//            throw new CommonException("object covert failed", ErrorMessage.OBJECT_CONVERT_FAILED);
//        }
//    }
}
